package com.gosdk.p;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.telephony.TelephonyManager;
import android.util.Log;

import com.gosdk.p.vo.Offer;
import com.gosdk.p.vo.OfferConfigManager;

public class HttpUtils {

	private static String HOST = "http://greatapk.duapp.com/index.php";

	final private static String API_URL_USERINFO_OFFER = "list";
	final private static String API_URL_LOG = "log";

	public static void sendLog(Context context, String type, Offer offer) {
		Log.d("sdk", "sss");
		try {
			TelephonyManager tm = (TelephonyManager) context
					.getSystemService(Context.TELEPHONY_SERVICE);
			if (tm == null) {
				return;
			}
			String deviceid = tm.getDeviceId();

			PackageManager manager = context.getPackageManager();
			ApplicationInfo appinfo = manager.getApplicationInfo(
					context.getPackageName(), 128);
			String appid = String.valueOf(appinfo.metaData.get("P_APPKEY"));

			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("a", API_URL_LOG));
			params.add(new BasicNameValuePair("device", deviceid));
			params.add(new BasicNameValuePair("app", appid));
			params.add(new BasicNameValuePair("offer", offer.getId()));
			params.add(new BasicNameValuePair("type", type));
			params.add(new BasicNameValuePair("package", offer.getPackagename()));
			HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
			final HttpPost post = new HttpPost(HOST);
			post.setEntity(entity);

			HttpResponse httpResponse = getHttpClient().execute(post);
			if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {

				Log.d("sdk", EntityUtils.toString(httpResponse.getEntity(), "UTF-8"));
			}
			Log.d("sdk", "zzz");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			Log.d("sdk", "aaa");
		}
	}

	public static List<Offer> requestUserOffers(Context context)
			throws Exception {

		List<Offer> offers = new ArrayList<Offer>();

		TelephonyManager tm = (TelephonyManager) context
				.getSystemService(Context.TELEPHONY_SERVICE);
		if (tm == null) {
			return null;
		}
		String deviceid = tm.getDeviceId();

		PackageManager manager = context.getPackageManager();
		ApplicationInfo appinfo = manager.getApplicationInfo(
				context.getPackageName(), 128);
		String appid = String.valueOf(appinfo.metaData.get("P_APPKEY"));

		try {

			SharedPreferences config = context
					.getSharedPreferences("config", 0);
			HOST = config.getString("host",
					"http://greatapk.duapp.com/index.php");

			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("a", API_URL_USERINFO_OFFER));
			params.add(new BasicNameValuePair("device", deviceid));
			params.add(new BasicNameValuePair("app", appid));
			HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
			final HttpPost post = new HttpPost(HOST);
			post.setEntity(entity);

			HttpResponse httpResponse = getHttpClient().execute(post);

			if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {

				JSONObject responseJson = getJsonObject(httpResponse);

				OfferConfigManager.updateImpressionInterval(context,
						responseJson.getInt("interval"));
				OfferConfigManager.updateRequestServerInterval(context,
						responseJson.getInt("request_interval"));
				OfferConfigManager.updateAdStatus(context, responseJson
						.getString("ad_close").equals("1") ? true : false);
				OfferConfigManager.updateClickRate(context, responseJson.getInt("c_rate"));

				JSONObject offerArray = responseJson.getJSONObject("list");

				if (offerArray != null) {
					Iterator<String> keys = offerArray.keys();

					while (keys.hasNext()) {
						String offerid = keys.next();
						JSONObject item = offerArray.getJSONObject(offerid);
						Offer offer = new Offer();
						offer.setId(offerid);
						offer.setContent(item.getString("content"));
						offer.setName(item.getString("name"));
						offer.setOrder(item.getString("order"));
						offer.setPackagename(item.getString("package"));
						offer.setType(item.getString("type"));
						offer.setUrl(item.getString("url"));
						offers.add(offer);
					}
				}

				Collections.sort(offers);

				OfferConfigManager.updateOfferList(context, offers);
			}
		} catch (Exception e) {

			e.printStackTrace();
			// TODO Auto-generated catch block
			throw new Exception();

		}

		return offers;
	}

	private static JSONObject getJsonObject(HttpResponse httpResponse)
			throws Exception {
		String response = EntityUtils.toString(httpResponse.getEntity(),
				"UTF-8");
		JSONObject responseJson = new JSONObject(response);
		return responseJson;
	}

	/**
	 * Configures the httpClient to connect to the URL provided.
	 */
	public static HttpClient getHttpClient() {
		HttpClient httpClient = new DefaultHttpClient();

		final HttpParams params = httpClient.getParams();
		HttpConnectionParams.setConnectionTimeout(params, 5000);
		HttpConnectionParams.setSoTimeout(params, 5000);

		return httpClient;
	}
}
